package cn.itsource.basic.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.system.UserInfo;
import cn.itsource.basic.other.config.exception.BusinessException;
import cn.itsource.org.domain.LoginInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class GetUserInfoUtil {

    /**
     * 获取到shopId
     * @return
     */
    public static Long getShopId(){

        Long shopId = getUserInfo().getShopId();

        Optional.ofNullable(shopId).orElseThrow(() -> new BusinessException("取不到shopId，请联系管理员"));
        return shopId;
    }

    /**
     * 获取到userId
     * @return
     */
    public static Long getUserId(){

        Long userId = getUserInfo().getUserId();

        Optional.ofNullable(userId).orElseThrow(() -> new BusinessException("取不到userId，请看老师插的三个眼，你是否漏了"));
        return userId;
    }
    public static String getPhone(){
        String phone = getUserInfo().getPhone();
        Optional.ofNullable(phone).orElseThrow(() -> new BusinessException("取不到phone,不知道为什么"));
        return phone;
    }

    /**
     * 获取到LoginInfo
     */
    public static LoginInfo getUserInfo(){
        //1.从request拿到token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String token = request.getHeader("token");

        //2.从redis中根据token查到这个对象
        RedisService redisService = SpringUtil.getBean(RedisService.class);

        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);

        return loginInfo;

    }


}
